<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="id?'编辑月卡':'增加月卡'" @back="$router.back()"/>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <!--
          el-form   :model  :rule
          el-form-item  prop 指定要用哪条规则
          el-input  v-model 绑定数据(双向绑定)
        -->
        <div class="form">
          <el-form ref="carInfoForm" :model="carInfoForm" :rules="carInfoRules" label-width="100px">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName"/>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carInfoForm.phoneNumber"/>
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carInfoForm.carNumber"/>
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand"/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeForm" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                type="daterange"
                placeholder="请选择有效日期"
                v-model="feeForm.payTime"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount"/>
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createCardAPI, getDetailAPI, updateCardAPI } from '@/api/card'

export default {
  data() {
    const validaeCarNumber = (rule, value, callback) => {
      // value: 用户在表单里输入的最新的数据
      // callback: 回调函数，必须调用 校验通过直接调用  如果是未通过 callback(new Error('错误信息'))
      const plateNumberRegex = /^[\u4E00-\u9FA5A][\da-zA-Z]{6}$/
      if (plateNumberRegex.test(value)) {
        callback()
      } else {
        callback(new Error('请输入符合规范的车牌号'))
      }
    }

    return {
      // 表单对象
      carInfoForm: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: ''
      },
      // 规则对象
      carInfoRules: {
        personName: [
          { required: true, message: '请输入车主姓名', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        carNumber: [
          { required: true, message: '请输入车辆号码', trigger: 'blur' },
          { validator: validaeCarNumber, trigger: 'blur' }
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }
        ]
      },
      // 缴费信息表单
      feeForm: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      // 缴费规则
      feeFormRules: {
        payTime: [
          { required: true, message: '请选择支付时间', trigger: 'blur' }
        ],
        paymentAmount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'blur' }
        ]
      },
      // 支付方式列表
      payMethodList: [
        { industryCode: 'AliPay', industryName: '支付宝' },
        { industryCode: 'WeChat', industryName: '微信' },
        { industryCode: 'Cash', industryName: '线下' }
      ],
      carInfoId: null,
      rechargeId: null
    }
  },
  methods: {
    handleSubmit() {
      // 表单校验
      this.$refs.carInfoForm.validate((valid) => {
        if (valid) {
          // 表单提交
          console.log(this.carInfoForm)
          console.log(this.feeForm)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    confirmAdd() {
      // 两个表单统一校验
      // 调用实例的validate方法
      // 1.串行校验  第一个表单校验通过再校验第二个表单
      // 2.并行校验
      this.$refs.carInfoForm.validate((valid) => {
        if (valid) {
          // 正常业务逻辑
          console.log('carInfoForm.Validate success')
        } else {
          console.log('error submit!! carInfoForm.Validate failed ')
          return false
        }
      })

      this.$refs.feeForm.validate(async valid => {
        if (valid) {
          // 正常业务逻辑
          // 两个表单校验完成后，执行业务逻辑
          const reqData = {
            ...this.carInfoForm,
            ...this.feeForm,
            cardStartDate: this.feeForm.payTime[0],
            cardEndDate: this.feeForm.payTime[1]
          }
          delete reqData.payTime
          console.log('======== 提交数据展示: ', reqData)

          // 需要区分新增和编辑
          if (this.id) {
            // 编辑
            reqData.carInfoId = this.carInfoId
            reqData.rechargeId = this.rechargeId
            const res = await updateCardAPI(reqData)
            console.log('======== 接口返回数据: ', res)
            if (res.code === 10000) {
              // 成功后跳转到月卡列表页
              // this.$router.back()
              // 成功后提示
              // this.$message.success('更新月卡成功')
            }
          } else {
            // 新增
            const res = await createCardAPI(reqData)
            console.log('======== 接口返回数据: ', res)
            if (res.code === 10000) {
              // 成功后跳转到月卡列表页
              // this.$router.back()
              // this.$router.push('/parking/card')
              // 成功后提示
              // this.$message.success('新增月卡成功')
            }
          }
          this.$message.success(`${this.id ? '更新月卡成功' : '新增月卡成功'}`)
          this.$router.back()
        } else {
          console.log('error submit!!  feeForm.Validate failed ')
          return false
        }
      })
    },
    handleReset() {
      console.log('======== 重置调用成功 ==========')
      // 表单重置
      this.$refs.carInfoForm.resetFields()
      this.$refs.feeForm.resetFields()
    },
    async getCardDetail(id) {
      // 获取详情
      const res = await getDetailAPI(id)
      console.log('======== 详情数据: ', res)
      if (res.code === 10000) {
        // 成功后展示详情数据
        this.carInfoForm = {
          personName: res.data.personName,
          phoneNumber: res.data.phoneNumber,
          carNumber: res.data.carNumber,
          carBrand: res.data.carBrand
        }
        this.feeForm = {
          payTime: [res.data.cardStartDate, res.data.cardEndDate],
          paymentAmount: res.data.paymentAmount,
          paymentMethod: res.data.paymentMethod
        }
        this.carInfoId = res.data.carInfoId
        this.rechargeId = res.data.rechargeId
      }
    }
  },
  mounted() {
    // console.log(' mounted ')
    // 取参数 注意: 取参数时 用 $route  而不是 this.$router
    const queryId = this.$route.query.id
    // console.log(' query: ', queryId)
    if (queryId) {
      // 取详情
      this.getCardDetail(queryId)
    }
  },
  computed: {
    // 路由参数
    id() {
      return this.$route.query.id
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
